package com.yuzhitong.shapi.util;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import a.a.a.MyApplication;

import java.util.List;

/**
 * Created by Brsya
 * CreateDate: 2022/4/18  14:02
 * Description:
 * 广告工具
 */
public class AdUtilManage {
    private static final int adWidth = 360;

    // 广告SDK管理
    private TTNativeExpressAd showAd;

    private AdUtilManage() {
    }

    private AdUtilManage(TTNativeExpressAd showAd) {
        this.showAd = showAd;
    }

    public TTNativeExpressAd getShowAd() {
        return showAd;
    }

    private void setShowAd(TTNativeExpressAd showAd) {
        this.showAd = showAd;
    }

    public static AdUtilManage initShow(Activity context, ViewGroup viewGroup, String adId) {
        return initShow(context, viewGroup, adId, 0);
    }

    public static AdUtilManage initShow(Activity activity, ViewGroup viewGroup, String adId, float height) {

        if (!MyApplication.isOpenAd()) {
            return null;
        }

        AdUtilManage adUtilManage = new AdUtilManage();

        if (activity == null) {
            return adUtilManage;
        }
        float width = activity.getApplicationContext().getResources().getDisplayMetrics().xdpi;
        if (OSUtils.isVivo()) {
            width = adWidth;
        }

        // 加载广告
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(activity);

        AdSlot adSlot = new AdSlot.Builder()
                // 广告ID 948498437 948498604
                .setCodeId(adId)
                .setSupportDeepLink(true)
                .setAdCount(1)
                // 期望模板广告view的size,单位dp
                .setExpressViewAcceptedSize(width, height)
                .setAdloadSeq(1)
                .build();

        viewGroup.removeAllViews();
        adNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int i, String s) {
                LoggerUtil.i("穿山甲广告加载失败 initShow： id:" + adId + "   :" + i + "--ss--" + s);
                viewGroup.setVisibility(View.GONE);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                LoggerUtil.e("广告加载成功");
                viewGroup.setVisibility(View.VISIBLE);
                for (TTNativeExpressAd adBean : list) {
                    viewGroup.removeAllViews();
                    View adRootView = adBean.getExpressAdView();
                    // 无法居中
                    //                    if (adRootView instanceof FrameLayout){
                    //                        FrameLayout fl = (FrameLayout) adRootView;
                    //                        for (int i = 0; i < fl.getChildCount(); i++) {
                    //                            if (!(fl.getChildAt(i) instanceof ViewGroup)){
                    //                                continue;
                    //                            }
                    //                            if (((ViewGroup) fl.getChildAt(i)).getChildCount() > 0){
                    //                                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) fl.getChildAt(i).getLayoutParams();
                    //                                layoutParams.gravity = Gravity.CENTER;
                    //                                fl.setLayoutParams(layoutParams);
                    //                            }
                    //                        }
                    //                    }
                    viewGroup.addView(adRootView);
                    adBean.render();
                    adBean.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
                        @Override
                        public void onShow() {
                            if (viewGroup != null) {
                                viewGroup.removeAllViews();
                                viewGroup.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onSelected(int i, String s, boolean b) {

                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                    adUtilManage.setShowAd(adBean);
                    break;
                }
            }
        });

        return adUtilManage;
    }

    public static AdUtilManage initShow(Activity activity, ViewGroup viewGroup, String adId, float height, TTNativeExpressAd.AdInteractionListener listener) {

        if (!MyApplication.isOpenAd()) {
            return null;
        }

        AdUtilManage adUtilManage = new AdUtilManage();

        if (activity == null) {
            return adUtilManage;
        }
        float width = activity.getApplicationContext().getResources().getDisplayMetrics().xdpi;
        if (OSUtils.isVivo()) {
            width = adWidth;
        }

        // 加载广告
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(activity);

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adId)
                .setSupportDeepLink(true)
                .setAdCount(1)
                // 期望模板广告view的size,单位dp
                .setExpressViewAcceptedSize(240, 0)
                .setAdloadSeq(1)
                .build();

        viewGroup.removeAllViews();
        adNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int i, String s) {
                LoggerUtil.i("穿山甲广告加载失败 initShow2 ： " + i + "--ss--" + s);
                viewGroup.setVisibility(View.GONE);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                LoggerUtil.e("广告加载成功");
                viewGroup.setVisibility(View.VISIBLE);
                for (TTNativeExpressAd adBean : list) {
                    viewGroup.removeAllViews();
                    View adRootView = adBean.getExpressAdView();
                    // 无法居中
                    //                    if (adRootView instanceof FrameLayout){
                    //                        FrameLayout fl = (FrameLayout) adRootView;
                    //                        for (int i = 0; i < fl.getChildCount(); i++) {
                    //                            if (!(fl.getChildAt(i) instanceof ViewGroup)){
                    //                                continue;
                    //                            }
                    //                            if (((ViewGroup) fl.getChildAt(i)).getChildCount() > 0){
                    //                                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) fl.getChildAt(i).getLayoutParams();
                    //                                layoutParams.gravity = Gravity.CENTER;
                    //                                fl.setLayoutParams(layoutParams);
                    //                            }
                    //                        }
                    //                    }
                    viewGroup.addView(adRootView);
                    adBean.render();
                    adBean.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
                        @Override
                        public void onShow() {
                            if (viewGroup != null) {
                                viewGroup.removeAllViews();
                                viewGroup.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onSelected(int i, String s, boolean b) {

                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                    adBean.setExpressInteractionListener(listener);
                    adUtilManage.setShowAd(adBean);
                    break;
                }
            }
        });

        return adUtilManage;
    }


    public static AdUtilManage initShowBanner(Activity activity, ViewGroup viewGroup, String adId, float height) {

        if (!MyApplication.isOpenAd()) {
            return null;
        }
        AdUtilManage adUtilManage = new AdUtilManage();

        if (activity == null) {
            return adUtilManage;
        }

        float width = activity.getApplicationContext().getResources().getDisplayMetrics().xdpi;
        if (OSUtils.isVivo()) {
            width = adWidth;
        }

        // 加载广告
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(activity);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adId) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1
                .setExpressViewAcceptedSize(width, height) //期望模板广告view的size,单位dp
                .setAdLoadType(TTAdLoadType.LOAD)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
                .build();

        adNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            //请求失败回调
            @Override
            public void onError(int code, String message) {
                LoggerUtil.i("穿山甲广告加载失败 initShowBanner ： " + code + "--ss--" + message);
                viewGroup.setVisibility(View.GONE);
            }

            //请求成功回调
            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                LoggerUtil.e("广告加载成功");
                viewGroup.setVisibility(View.VISIBLE);
                for (TTNativeExpressAd adBean : ads) {
                    viewGroup.removeAllViews();
                    viewGroup.addView(adBean.getExpressAdView());
                    adBean.render();
                    adBean.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
                        @Override
                        public void onShow() {
                            viewGroup.removeAllViews();
                            viewGroup.setVisibility(View.GONE);
                        }

                        @Override
                        public void onSelected(int i, String s, boolean b) {

                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                    adUtilManage.setShowAd(adBean);
                    break;
                }
            }
        });
        return adUtilManage;
    }

    public static AdUtilManage initShowSplash(Activity activity, ViewGroup viewGroup, String adId, GotoHomeListener gotoHomeListener, TTSplashAd.AdInteractionListener listener) {

        if (!MyApplication.isOpenAd()) {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (gotoHomeListener != null) {
                        gotoHomeListener.gotoHome();
                    }
                    LoggerUtil.e("未打开广告");
                }
            }, 2000);
            return null;
        }
        //        float scaledDensity = activity.getResources().getDisplayMetrics().scaledDensity;
        //        float density = activity.getResources().getDisplayMetrics().density;
        int width = activity.getResources().getDisplayMetrics().widthPixels;
        int height = activity.getResources().getDisplayMetrics().heightPixels;
        float xdpi = activity.getResources().getDisplayMetrics().xdpi;
        float ydpi = activity.getResources().getDisplayMetrics().ydpi;

        AdUtilManage adUtilManage = new AdUtilManage();
        // 加载广告
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(activity);

        LoggerUtil.i("setImageAcceptedSize" + width + "--" + (int) (580 * height / 640));
        LoggerUtil.i("setExpressViewAcceptedSize" + 360 + "--" + ydpi);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adId)
                //不区分渲染方式，要求开发者同时设置setImageAcceptedSize（单位：px）和setExpressViewAcceptedSize（单位：dp ）接口，不同时设置可能会导致展示异常。
                .setImageAcceptedSize(width, height)
                //                .setExpressViewAcceptedSize(xdpi, ydpi)
                .setAdLoadType(TTAdLoadType.LOAD)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
                .build();

        adNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            //请求失败回调
            @Override
            public void onError(int code, String message) {
                LoggerUtil.i("穿山甲广告加载失败 initShowSplash ： " + code + "--ss--" + message);
                viewGroup.setVisibility(View.GONE);
                if (gotoHomeListener != null) {
                    gotoHomeListener.gotoHome();
                }
            }

            @Override
            public void onTimeout() {
                if (gotoHomeListener != null) {
                    gotoHomeListener.gotoHome();
                }
            }

            @Override
            public void onSplashAdLoad(TTSplashAd ttSplashAd) {
                if (ttSplashAd == null) {
                    if (gotoHomeListener != null) {
                        gotoHomeListener.gotoHome();
                    }
                    return;
                }
                ttSplashAd.setSplashInteractionListener(listener);
                //获取SplashView
                View view = ttSplashAd.getSplashView();
                if (view != null && viewGroup != null && !activity.isFinishing()) {
                    if (gotoHomeListener != null) {
                        gotoHomeListener.showSuccess();
                    }
                    viewGroup.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width =屏幕宽；height >=75%屏幕高
                    viewGroup.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                    //ad.setNotAllowSdkCountdown();
                } else {
                    //开发者处理跳转到APP主页面逻辑
                    if (gotoHomeListener != null) {
                        gotoHomeListener.gotoHome();
                    }
                }
            }
        }, 4000);
        return adUtilManage;
    }


    public static AdUtilManage initBigVideo(Activity activity, String adId) {

        if (!MyApplication.isOpenAd()) {
            return null;
        }
        AdUtilManage adUtilManage = new AdUtilManage();

        if (activity == null) {
            return adUtilManage;
        }
        float width = activity.getApplicationContext().getResources().getDisplayMetrics().xdpi;
        if (OSUtils.isVivo()) {
            width = adWidth;
        }
        int widthScreen = activity.getResources().getDisplayMetrics().widthPixels;
        int heightScreen = activity.getResources().getDisplayMetrics().heightPixels;

        int adWidth = Math.max(widthScreen, heightScreen);
        int adHeight = Math.min(widthScreen, heightScreen);


        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adId) //广告位id
                .setAdLoadType(TTAdLoadType.LOAD)
                .setExpressViewAcceptedSize(480,320)
                .build();

        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                LoggerUtil.e("广告请求失败, " + i + " , " + s);
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                if (!activity.isFinishing()) {
                    ttFullScreenVideoAd.showFullScreenVideoAd(activity, TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);
                }
            }

            @Override
            public void onFullScreenVideoCached() {

            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {

            }
        }
//        new TTAdNative.NativeExpressAdListener() {
//            //请求广告失败
//            @Override
//            public void onError(int code, String message) {
//            }
//            //请求广告成功
//            @Override
//            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
//                TTNativeExpressAd ttNativeExpressAd = ads.get(0);
//                ttNativeExpressAd.render();
//                adUtilManage.setShowAd(ttNativeExpressAd);
//                if (!activity.isFinishing()) {
//                    ttNativeExpressAd.showInteractionExpressAd(activity);
//                }
//            }
//        }
        );

        return adUtilManage;

    }

    public static void destroy(AdUtilManage adUtilManage) {
        if (adUtilManage != null && adUtilManage.getShowAd() != null) {
            adUtilManage.getShowAd().destroy();
        }
    }

    public interface GotoHomeListener {
        void showSuccess();

        void gotoHome();
    }
}
